#include "named_pipe.h"

int main() {
    bool ret = creatFifo(NAMED_PIPE); // creatFifo只是创建了一个命名管道，还需要我们手动打开管道文件
    assert(ret);
    (void)ret;

    // 命名管道的读端会阻塞等待写端的打开
    // 但是写端不会等待读端打开
    cout << "server begin" << endl;
    int read_fd = open(NAMED_PIPE, O_RDONLY);
    cout << "server end" << endl;
    assert(read_fd >= 0);

    char buffer[1024];
    while (true) {
        ssize_t size = read(read_fd, buffer, sizeof(buffer) - 1);
        if (size > 0) { // 从管道中读到数据了
            buffer[size] = '\0';
            cout << "client->server# " << buffer << endl;
        }
        else if (size == 0) { // 说明管道写端关闭，读端也要关闭
            cout << "client quit, me too!" << endl;
            break;
        }
        else {
            cout << "error message: " << strerror(errno) << endl;
            exit(-1);
        }
    }

    close(read_fd); // 关闭管道文件
    removeFifo(NAMED_PIPE); // 删除命名管道

    return 0;
}